package com.tencent.user.service.impl;

import com.tencent.basic.exception.BusinessException;
import com.tencent.basic.service.serviceimpl.BaseServiceImpl;
import com.tencent.basic.util.Md5Utils;
import com.tencent.basic.util.StrUtils;
import com.tencent.org.domain.Emp;
import com.tencent.user.domain.Logininfo;
import com.tencent.user.domain.User;
import com.tencent.user.dto.UserDto;
import com.tencent.user.mapper.LogininfoMapper;
import com.tencent.user.mapper.UserMapper;
import com.tencent.user.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * 业务实现类：
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JavaMailSender javaMailSender;

    @Override
    @Transactional
    public void phoneRegister(UserDto userDto) {
        // 1.检验空值
        String phone = userDto.getPhone();
        String phoneCode = userDto.getPhoneCode();
        String pwd = userDto.getPwd();
        String rePwd = userDto.getRePwd();
        if (phone.isEmpty() || phoneCode.isEmpty() || pwd.isEmpty() || rePwd.isEmpty()){
            throw new BusinessException("信息必须全部填写");
        }

        // 2.检验两次输入的密码是否相等
        if(!pwd.equals(rePwd)){
            throw new BusinessException("两次输入的密码不一致，请冲洗输入");
        }

        // 3.检验短信验证码是否过期或者正确
        // 读取数据库中的短信验证码
        Object codeObj = redisTemplate.opsForValue().get("register:" + phone);
        // 如果数据库中的手机验证码为空，要么是第一次获取，要么就是失效了
        if (codeObj == null){
            throw new BusinessException("短信验证码已经失效，请重兴获取");
        }
        // 如果数据库中的手机验证码跟前端传入的不一样，则说明输错了
        if (!codeObj.toString().split(":")[0].equals(phoneCode)){
            throw new BusinessException("短信验证码输入错误");
        }
        
        // 4.添加到数据库
        // 讲userDto对象转为User对象
        User user = userDto2User(userDto);
        // 将user对象转为Logininfo对象
        Logininfo logininfo = user2Logininfo(user);
        // 先吧logininfo添加到数据库过去自增id
        logininfoMapper.add(logininfo);
        // 再把user添加到数据库中
        user.setLogininfoId(logininfo.getId());
        userMapper.add(user);
    }

    @Override
    public void emailRegister(UserDto userDto) throws MessagingException {
        // 1.检验空值
        String email = userDto.getEmail();
        String pwd = userDto.getPwd();
        String rePwd = userDto.getRePwd();
        if(email.isEmpty() || pwd.isEmpty() || rePwd.isEmpty()){
            throw new BusinessException("信息必须全部填写");
        }
        // 2.检验两次输入的密码是否相等
        if(!pwd.equals(rePwd)){
            throw new BusinessException("两次输入的密码不一致，请冲洗输入");
        }

        // 3.发送复杂有机胺
        // 创建一个复杂邮件
        MimeMessage message = javaMailSender.createMimeMessage();
        // 传入的信息， 可以带附件， 编码格式
        MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
        // 发件人
        helper.setFrom("389616765@qq.com");
        // 收件人
        helper.setTo(userDto.getEmail());
        // 邮件标题
        helper.setSubject("注册成功激活");
        // 邮件内容
        helper.setText("<h1>恭喜成为东京冷会员!!!</h1><h3><a href='http://127.0.0.1:8080/shop/active/'>点击该链接跳转到登录界面开启神秘的世界</a></h3>",true);
        // 发送邮件
        javaMailSender.send(message);

        // 4.添加到数据库
        // 讲userDto对象转为User对象
        User user = userDto2User(userDto);
        // 将user对象转为Logininfo对象
        Logininfo logininfo = user2Logininfo(user);
        // 先吧logininfo添加到数据库过去自增id
        logininfoMapper.add(logininfo);
        // 再把user添加到数据库中
        user.setLogininfoId(logininfo.getId());
        userMapper.add(user);
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user, logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        return logininfo;
    }

    private User userDto2User(UserDto userDto) {
        User user = new User();
        if(!userDto.getPhone().equals(null) && !"".equals(userDto.getPhone())){
            user.setUsername(userDto.getPhone());
        }else{
            user.setUsername(userDto.getEmail());
        }

        user.setPhone(userDto.getPhone());
        user.setEmail(userDto.getEmail());
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(userDto.getPwd() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        user.setState(1);
        return user;
    }

    @Override
    @Transactional
    public void add(User user) {
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);


        // 保存logininfo
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user, logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        logininfoMapper.add(logininfo);

        user.setLogininfoId(logininfo.getId());
        super.add(user);
    }


    @Override
    @Transactional
    public void update(User user) {
        // 处理加盐加密
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        super.update(user);
        // 获取登录信息id
        Long logininfoId = userMapper.findById(user.getId()).getLogininfoId();
        // 创建logininfo
        Logininfo logininfo = logininfoMapper.findById(logininfoId);
        // 新数据覆盖旧数据
        BeanUtils.copyProperties(user, logininfo);
        logininfoMapper.update(logininfo);
    }


    @Override
    @Transactional
    public void del(Long id) {
        User user = userMapper.findById(id);
        logininfoMapper.del(user.getLogininfoId());

        super.del(id);
    }
}
